import numpy as np
import pandas as pd
import os
import colorama
import warnings
warnings.filterwarnings("ignore")

root_path=os.path.join(os.getcwd(),".\\Data_process\\Filter")

colorama.init(autoreset=True)
TEXT_COLOR_RED = colorama.Fore.RED
TEXT_COLOR_GREEN = colorama.Fore.GREEN
TEXT_COLOR_YELLOW = colorama.Fore.YELLOW
TEXT_COLOR_END = colorama.Fore.RESET

# initial_sweep_coef={
#             "HTL.d": 1.0,
#             "LiF.d":1.0,
#             "Cathode.d": 1.0,
#             "CPL.d": 1.0,
#             "IL2.d":1.0,
#             "SiO.d": 1.0,
#             "SiON-B.d": 1.0,
#             "SiON-i.d":1.0,
#             "PAS.d":1.0,
#             "SiON-i2.d": 1.0,
#             "SiN.d": 1.0
#         }

def fout(input_file_name, process_name, out_format):
    info_list = input_file_name.split(".")[0].split("-")[0].split("_")
    fout_prefix = f'{process_name}_' + "_".join(info_list[1:])
    ntry = 0
    while True:
        if ntry == 0:
            fout = fout_prefix + f'.{out_format}'
        else:
            fout = fout_prefix + '-%d.%s' % (ntry, out_format)
        if os.access(os.path.join(root_path, fout), os.F_OK):
            ntry += 1
        else:
            break
    return fout
def main(Ref_df ,Per_df,coef):
    check_bool=True
    while check_bool:
        to_str = lambda x: str(x)
        to_float = lambda x: float(x)
        df_ref =Ref_df.applymap(to_float)
        df_src =Per_df.applymap(to_float)

        df_ref_cols,df_src_cols=df_ref.columns.tolist(),df_src.columns.tolist()

        # initial_sweep=df_src_cols[:-4]
        # initial_sweep_coef = {f"{sweep_name}": 1 for sweep_name in initial_sweep }

        conge_sweep=list(set(df_ref_cols)&set(df_src_cols))
        conge_sweep.sort(key=df_ref_cols.index)
        print("columns that used to matching _Ref and _%xx: ",TEXT_COLOR_GREEN+"%s"%(conge_sweep,)+TEXT_COLOR_END)

        coeff_dict={ f"{sweep_name}":1 for sweep_name in conge_sweep}
        if "SiON-B.d" in conge_sweep:
            print("Find SiON-B.d in Common Key Cols,Multiple Coefs")
            coeff_dict["SiON-B.d"] = 1 - 0.01 * int(coef)
        else:
            print("Do Not Find SiON-B.d in Common Key Cols,Do Not Multiple Coefs")


        query_field = list(coeff_dict.keys())
        coeffs_Series = pd.Series(list(coeff_dict.values()), index=query_field)

        # result_field =df_src_cols[-4:]
        # result_field.sort(key=df_src_cols.index)
        # output_field = query_field + result_field
        output_field=df_src_cols


        df_ref_tmp = (df_ref.loc[:, query_field] * coeffs_Series)
        df_src_tmp = df_src.loc[:, output_field]
        matched_df=pd.merge(df_ref_tmp,df_src_tmp, on=query_field,how="inner")

        print(f"matched_df={len(matched_df)}")
        print(f"matched_df={len(Ref_df)}")
        
        if len(matched_df)!=len(Ref_df):
            print("Attention! When Matching With Sweep : %s, Rows of Ref Do Not Equal to _xx "%(query_field,))
            check_bool = input('Plesse Check Your Configration,Then  Enter [yes] to Re_Matching Else Stop Matchhing: ').strip().lower()=="yes"
        else:
            check_bool=False
    return matched_df

if __name__ == '__main__':
    root_path=os.getcwd()
    inp_r_m= input('Enter file you want matching ,which coresponding to [ Filtered_R_Ref.csv  Setfos_R_5.csv ] ": \n').strip().split()
    
    df_ref = pd.read_csv(os.path.join(root_path,inp_r_m[0]))
    df_src = pd.read_csv(os.path.join(root_path,inp_r_m[1]))
    info_list = inp_r_m[1].split(".")[0].split("-")[0].split("_")
    if info_list[-1].isdigit():
        coef=info_list[-1]
    else:
        print("Can not recognize coef from File_name of %s"%inp_r_m[1])
        print(f"inp_r_m={inp_r_m}")
        coef=input("Please set the coef of Sion.B.d for Ref :").strip()
    matched_df=main(df_ref ,df_src,coef)
    fout=fout(inp_r_m[1],"Matched","csv")
    matched_df.to_csv(os.path.join(root_path,fout), index=False)
    print('Total rows:' + TEXT_COLOR_GREEN + ' %d' % (len(matched_df)) + TEXT_COLOR_END)
    print('Write output file ' + TEXT_COLOR_GREEN + "%s" % (fout,) + TEXT_COLOR_END + ' successfully!')